#!/usr/bin/python
"""
#
#   read_project_prameter_file module
#
#       get_keys(parameter_file)
#
#
#   Copyright (C) 2007 Leo Goodstadt
#
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the GNU General Public License
#   as published by the Free Software Foundation; version 2
#   of the License
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
"""


import sys, os, re,general_util, get_parameter_path


# 
# 
# add self to search path for testing
if __name__ == '__main__':
    sys.path.append(".")

    


def self_substitute (params):

    regex_str = "\$\(([^()]+)\)"
    regex = re.compile(regex_str)
    while 1:
        any_substituted = False
        for k, v in params.iteritems():
            match = regex.search(v)
            if match:
                substitute_k = match.group(1)
                if substitute_k in params:
                    params[k] = re.sub("\$\(%s\)" % substitute_k, 
                                        params[substitute_k], params[k])
                    any_substituted = True
        if not any_substituted:
            break
            
            
        



def get_keys(parameter_file):
    '''
    Read parameters from the parameter directory

        Reads KEY=VALUE format parameters from a file
        which can be found with reference to the module file
    '''

        

    # 
    #   check that can find parameter file
    # 
    param_file_name = os.path.join(get_parameter_path.parameter_path, parameter_file)
    if not os.path.isfile(param_file_name):
        general_util.die_error("Parameter file %s is missing from %s !!" % 
                               (parameter_file, get_parameter_path.parameter_path))
    
    # 
    #   read parameter file
    # 
    param_file = open(param_file_name)
    line_re = re.compile(r'^([^#]?.*?)[ \t]*=[ \t]*(.*?)[ \t]*$')
    params = dict()
    for line in param_file:
        match = line_re.search(line.rstrip())
        if not match:
            continue
        key,value = match.groups()
        params[key.upper()] =value

    self_substitute (params)
    return params


if __name__ == '__main__':
    for k, v in get_keys('PARAMETERS').iteritems():
        print "%30s=%s" % (k, v)
